import { onMounted, ref } from 'vue'
import { ceil, floor, random, shuffle } from 'lodash-es'

interface GameConfig {
  container?: Ref<HTMLElement | undefined>,   // cardNode容器
  cardNum: number,                            // card类型属性
  layerNum: number,                           // card层数
  trap?: boolean,                             // 是否从nodes中剔除已选节点
  delNode?: boolean,                          // 是否从nodes中剔除已选节点
  events?: GameEvents                          // 游戏事件
}

interface GameEvents {
  clickCallback?: () => void,
  dropCallback?: () => void,
  winCallback?: () => void,
  loseCallback?: () => void
}

type CardNode = {
  id: string // 节点id，
  type: number // 类型
  zIndex: number // 图层
  index: number // 所在图层的索引
  parents: CardNode[] // 父节点
  row: number // 行
  column: number // 列
  top: number
  left: number
  state: number // 是否可点击：0-无状态，1-可点击，2-已选，3-已消除
}

const defaultGameConfig: GameConfig = {
  cardNum: 4,
  layerNum: 2,
  trap: true,
  delNode: false
}

export function useGame(config: GameConfig) {
  const { container, cardNum, layerNum, trap, delNode, events={} } = {...defaultGameConfig, ...config};
  const historyList = ref<CardNode[]>([]);
  const backFlag = ref(false);
  const removeFlag = ref(false)
  const removeList = ref<CardNode[]>([])
  const preNode = ref<CardNode | null>(null)
  const size = 40
  const isTrap = trap && floor(random(0, 100)) !== 50
  const nodes = ref<CardNode[]>([])
  const indexSet = new Set();
  let perFloorNodes: CardNode[] = []

  // 生成节点池
  const itemTypes = (new Array(cardNum).fill(0)).map((_,index) => index+1)
  let itemList: number[] = []
  const selectNodes = ref<CardNode[]>([]);
  for(let i = 0;i<3*layerNum; i++) {
    itemList = [...itemList, ...itemTypes]
  }
  if (isTrap) {

  }
}
